import axios from 'axios'
import type { ApiResult } from '@/types/auth'
import type { 
  ProcessCategoryPageParams, ProcessCategoryPageResponse, ProcessCategoryApiResponse, ProcessCategoryCreateDto, ProcessCategoryUpdateDto, ProcessCategory,
  ProcessQueryParams, ProcessApiResponse, ProcessCreateDto, ProcessUpdateDto, Process,
  ProcessFlowQueryParams, ProcessFlowApiResponse, ProcessFlowCreateDto, ProcessFlowUpdateDto, ProcessFlow, ProcessFlowStep
} from '@/types/process'

const processApi = axios.create({
  baseURL: 'http://localhost:5237/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
processApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    console.log('发送请求:', config.method?.toUpperCase(), config.url, config.params || config.data)
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一错误处理
processApi.interceptors.response.use(
  (response) => {
    console.log('收到响应:', response.config.url, response.data)
    return response
  },
  (error) => {
    console.error('ProcessManagementApi错误:', error)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误数据:', error.response.data)
    }
    return Promise.reject(error)
  }
)

// 获取工序分页列表
export const getProcessPage = async (params?: ProcessQueryParams): Promise<ProcessApiResponse> => {
  try {
    console.log('开始获取工序数据，参数:', params)
    const response = await processApi.get('/Process', { params })
    console.log('工序API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('获取工序分页数据失败:', error)
    if (error.code === 'ERR_NETWORK') {
      return {
        msg: '网络连接失败，请检查后端服务是否启动',
        code: 500,
        data: null as any,
        pageData: [],
        totaCount: 0,
        totaPage: 0
      }
    }
    return {
      msg: error.response?.data?.message || '获取工序分页数据失败，请重试',
      code: error.response?.status || 500,
      data: null as any,
      pageData: [],
      totaCount: 0,
      totaPage: 0
    }
  }
}

// 根据ID获取工序详情
export const getProcessById = async (id: number): Promise<ApiResult<Process>> => {
  try {
    console.log('开始获取工序详情，ID:', id)
    const response = await processApi.get(`/Process/${id}`)
    console.log('工序详情API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('获取工序详情失败:', error)
    return {
      msg: error.response?.data?.msg || '获取工序详情失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 创建新工序
export const createProcess = async (data: ProcessCreateDto): Promise<ApiResult<Process>> => {
  try {
    console.log('开始创建工序，数据:', data)
    const response = await processApi.post('/Process', data)
    console.log('创建工序API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('创建工序失败:', error)
    return {
      msg: error.response?.data?.msg || '创建工序失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 更新工序
export const updateProcess = async (data: ProcessUpdateDto): Promise<ApiResult<Process>> => {
  try {
    console.log('开始更新工序，数据:', data)
    const response = await processApi.put('/Process', data)
    console.log('更新工序API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('更新工序失败:', error)
    return {
      msg: error.response?.data?.msg || '更新工序失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 删除工序
export const deleteProcess = async (id: number): Promise<ApiResult<any>> => {
  try {
    console.log('开始删除工序，ID:', id)
    const response = await processApi.delete(`/Process/${id}`)
    console.log('删除工序API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('删除工序失败:', error)
    return {
      msg: error.response?.data?.msg || '删除工序失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 批量删除工序
export const batchDeleteProcesses = async (ids: number[]): Promise<ApiResult<any>> => {
  try {
    console.log('开始批量删除工序，IDs:', ids)
    const response = await processApi.delete('/Process/batch', { data: ids })
    console.log('批量删除工序API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('批量删除工序失败:', error)
    return {
      msg: error.response?.data?.msg || '批量删除工序失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 导出工序到Excel
export const exportProcesses = async (params?: {
  NumberOrName?: string
  ProcessCategoryId?: number
  Department?: string
  ResponsiblePerson?: string
  IsActive?: boolean
}) => {
  try {
    console.log('开始导出工序，参数:', params)
    const response = await processApi.get('/Process/export', { 
      params,
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名
    const fileName = `工序列表导出_${new Date().toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '_')}.xlsx`
    link.download = fileName
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('工序导出成功')
    return { success: true, message: '导出成功' }
  } catch (error: any) {
    console.error('导出工序失败:', error)
    return { 
      success: false, 
      message: error.response?.data?.message || '导出失败，请重试' 
    }
  }
}

// 获取工序分类分页数据
export const getProcessCategoryPage = async (params?: ProcessCategoryPageParams): Promise<ProcessCategoryApiResponse> => {
  try {
    console.log('开始获取工序分类数据，参数:', params)
    const response = await processApi.get('/ProcessCategory/page', { params })
    console.log('工序分类API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('获取工序分类分页数据失败:', error)
    if (error.code === 'ERR_NETWORK') {
      return {
        msg: '网络连接失败，请检查后端服务是否启动',
        code: 500,
        data: null as any,
        pageData: [],
        totaCount: 0,
        totaPage: 0
      }
    }
    return {
      msg: error.response?.data?.message || '获取工序分类分页数据失败，请重试',
      code: error.response?.status || 500,
      data: null as any,
      pageData: [],
      totaCount: 0,
      totaPage: 0
    }
  }
}

// 获取激活的工序分类（用于下拉选择）
export const getActiveProcessCategories = async (): Promise<{ code: number; msg: string; data: ProcessCategory[] }> => {
  try {
    console.log('开始获取激活的工序分类数据')
    const response = await processApi.get('/ProcessCategory/active')
    console.log('激活工序分类API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('获取激活工序分类失败:', error)
    if (error.code === 'ERR_NETWORK') {
      return {
        code: 500,
        msg: '网络连接失败，请检查后端服务是否启动',
        data: []
      }
    }
    return {
      code: error.response?.status || 500,
      msg: error.response?.data?.message || '获取激活工序分类失败，请重试',
      data: []
    }
  }
}

// 导出工序分类到Excel
export const exportProcessCategories = async (params?: { NumberOrName?: string; IsActive?: boolean }) => {
  try {
    console.log('开始导出工序分类，参数:', params)
    const response = await processApi.get('/ProcessCategory/export', { 
      params,
      responseType: 'blob' // 重要：指定响应类型为blob
    })
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名
    const fileName = `工序分类导出_${new Date().toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '_')}.xlsx`
    link.download = fileName
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('工序分类导出成功')
    return { success: true, message: '导出成功' }
  } catch (error: any) {
    console.error('导出工序分类失败:', error)
    return { 
      success: false, 
      message: error.response?.data?.message || '导出失败，请重试' 
    }
  }
}

// 创建工序分类
export const createProcessCategory = async (data: ProcessCategoryCreateDto): Promise<ApiResult<ProcessCategory>> => {
  try {
    console.log('开始创建工序分类，数据:', data)
    const response = await processApi.post('/ProcessCategory', data)
    console.log('创建工序分类API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('创建工序分类失败:', error)
    return {
      msg: error.response?.data?.msg || '创建工序分类失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 更新工序分类
export const updateProcessCategory = async (data: ProcessCategoryUpdateDto): Promise<ApiResult<ProcessCategory>> => {
  try {
    console.log('开始更新工序分类，数据:', data)
    const response = await processApi.put('/ProcessCategory', data)
    console.log('更新工序分类API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('更新工序分类失败:', error)
    return {
      msg: error.response?.data?.msg || '更新工序分类失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 删除工序分类
export const deleteProcessCategory = async (id: number): Promise<ApiResult<any>> => {
  try {
    console.log('开始删除工序分类，ID:', id)
    const response = await processApi.delete(`/ProcessCategory/${id}`)
    console.log('删除工序分类API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('删除工序分类失败:', error)
    return {
      msg: error.response?.data?.msg || '删除工序分类失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 生成工序编码
export const generateProcessCode = async (): Promise<ApiResult<string>> => {
  try {
    const response = await processApi.get('/Process/generate-code')
    return response.data
  } catch (error) {
    console.error('生成工序编码失败:', error)
    throw error
  }
}

// ========== 工艺流程相关API ==========

// 获取工艺流程分页列表
export const getProcessFlowPage = async (params?: ProcessFlowQueryParams): Promise<ProcessFlowApiResponse> => {
  try {
    console.log('开始获取工艺流程数据，参数:', params)
    const response = await processApi.get('/ProcessFlow', { params })
    console.log('工艺流程API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('获取工艺流程分页数据失败:', error)
    if (error.code === 'ERR_NETWORK') {
      return {
        msg: '网络连接失败，请检查后端服务是否启动',
        code: 500,
        data: null as any,
        pageData: [],
        totaCount: 0,
        totaPage: 0
      }
    }
    return {
      msg: error.response?.data?.message || '获取工艺流程分页数据失败，请重试',
      code: error.response?.status || 500,
      data: null as any,
      pageData: [],
      totaCount: 0,
      totaPage: 0
    }
  }
}

// 根据ID获取工艺流程详情
export const getProcessFlowById = async (id: number): Promise<ApiResult<ProcessFlow>> => {
  try {
    console.log('开始获取工艺流程详情，ID:', id)
    const response = await processApi.get(`/ProcessFlow/${id}`)
    console.log('工艺流程详情API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('获取工艺流程详情失败:', error)
    return {
      msg: error.response?.data?.msg || '获取工艺流程详情失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 根据流程ID获取工序步骤列表
export const getProcessFlowSteps = async (processFlowId: number): Promise<ApiResult<ProcessFlowStep[]>> => {
  try {
    console.log('开始获取工序步骤列表，流程ID:', processFlowId)
    // 尝试多个可能的API endpoint
    const endpoints = [
      `/ProcessFlow/${processFlowId}/steps`,
      `/ProcessFlow/${processFlowId}/Steps`, 
      `/ProcessFlowStep/ByFlowId/${processFlowId}`,
      `/ProcessFlowSteps/${processFlowId}`,
      `/ProcessFlow/${processFlowId}/ProcessSteps`
    ]
    
    for (const endpoint of endpoints) {
      try {
        console.log('尝试API endpoint:', endpoint)
        const response = await processApi.get(endpoint)
        console.log('工序步骤API响应:', response.data)
        if (response.data && response.data.code === 200) {
          return response.data
        }
      } catch (endpointError: any) {
        console.log(`Endpoint ${endpoint} 失败:`, endpointError.response?.status)
        continue
      }
    }
    
    // 如果所有endpoint都失败，返回空数组
    console.warn('所有工序步骤API endpoint都失败，返回空数组')
    return {
      msg: '获取工序步骤成功',
      code: 200,
      data: []
    }
    
  } catch (error: any) {
    console.error('获取工序步骤失败:', error)
    return {
      msg: error.response?.data?.msg || '获取工序步骤失败，请重试',
      code: error.response?.status || 500,
      data: []
    }
  }
}

// 创建新工艺流程
export const createProcessFlow = async (data: ProcessFlowCreateDto): Promise<ApiResult<ProcessFlow>> => {
  try {
    console.log('开始创建工艺流程，数据:', data)
    const response = await processApi.post('/ProcessFlow', data)
    console.log('创建工艺流程API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('创建工艺流程失败:', error)
    return {
      msg: error.response?.data?.msg || '创建工艺流程失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 更新工艺流程
export const updateProcessFlow = async (data: ProcessFlowUpdateDto): Promise<ApiResult<ProcessFlow>> => {
  try {
    console.log('开始更新工艺流程，数据:', data)
    const response = await processApi.put('/ProcessFlow', data)
    console.log('更新工艺流程API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('更新工艺流程失败:', error)
    return {
      msg: error.response?.data?.msg || '更新工艺流程失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 删除工艺流程
export const deleteProcessFlow = async (id: number): Promise<ApiResult<any>> => {
  try {
    console.log('开始删除工艺流程，ID:', id)
    const response = await processApi.delete(`/ProcessFlow/${id}`)
    console.log('删除工艺流程API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('删除工艺流程失败:', error)
    return {
      msg: error.response?.data?.msg || '删除工艺流程失败，请重试',
      code: error.response?.status || 500,
      data: null as any
    }
  }
}

// 批量删除工艺流程
export const batchDeleteProcessFlows = async (ids: number[]): Promise<ApiResult<any>> => {
  try {
    console.log('开始批量删除工艺流程，IDs:', ids)
    const response = await processApi.delete('/ProcessFlow/batch', { data: ids })
    console.log('批量删除工艺流程API响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('批量删除工艺流程失败:', error)
    return {
      msg: error.response?.data?.msg || '批量删除工艺流程失败，请重试',
      code: error.response?.status || 500,
      data: null
    }
  }
}

// 导出工艺流程步骤到Excel
export const exportProcessFlowSteps = async (processFlowId: number): Promise<void> => {
  try {
    console.log('开始导出工艺流程步骤，工艺流程ID:', processFlowId)
    
    const response = await processApi.post(`/ProcessFlow/${processFlowId}/steps/export`, {}, {
      responseType: 'blob'
    })
    
    console.log('导出工艺流程步骤API响应:', response)
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 从响应头中获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition']
    let fileName = `工艺流程步骤_${processFlowId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`
    
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (fileNameMatch && fileNameMatch[1]) {
        fileName = fileNameMatch[1].replace(/['"]/g, '')
        // 解码URL编码的文件名
        try {
          fileName = decodeURIComponent(fileName)
        } catch (e) {
          console.warn('文件名解码失败，使用默认文件名')
        }
      }
    }
    
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('工艺流程步骤导出成功，文件名:', fileName)
  } catch (error: any) {
    console.error('导出工艺流程步骤失败:', error)
    throw new Error(error.response?.data?.message || '导出失败，请重试')
  }
}

// 打印工艺流程详情到PDF
export const printProcessFlowDetailsToPdf = async (processFlowId: number): Promise<void> => {
  try {
    console.log('开始打印工艺流程详情，工艺流程ID:', processFlowId)
    
    const response = await processApi.post(`/ProcessFlow/${processFlowId}/print`, {}, {
      responseType: 'blob'
    })
    
    console.log('打印工艺流程详情API响应:', response)
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/pdf' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 从响应头中获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition']
    let fileName = `工艺流程详情_${processFlowId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.pdf`
    
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (fileNameMatch && fileNameMatch[1]) {
        fileName = fileNameMatch[1].replace(/['"]/g, '')
        // 解码URL编码的文件名
        try {
          fileName = decodeURIComponent(fileName)
        } catch (e) {
          console.warn('文件名解码失败，使用默认文件名')
        }
      }
    }
    
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('工艺流程详情打印成功，文件名:', fileName)
  } catch (error: any) {
    console.error('打印工艺流程详情失败:', error)
    throw new Error(error.response?.data?.message || '打印失败，请重试')
  }
}

// 导出工艺流程步骤到Excel
export const exportProcessFlowStepsToExcel = async (processFlowId: number): Promise<void> => {
  try {
    console.log('开始导出工艺流程步骤到Excel，ID:', processFlowId)
    
    const response = await processApi.post(`/ProcessFlow/${processFlowId}/steps/export`, {}, {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition']
    let fileName = `工艺流程步骤_${processFlowId}_${new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')}.xlsx`
    
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename=(.+)/)
      if (fileNameMatch) {
        fileName = fileNameMatch[1].replace(/"/g, '')
      }
    }
    
    // 创建并点击下载链接
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('工艺流程步骤导出成功，文件名:', fileName)
  } catch (error: any) {
    console.error('导出工艺流程步骤失败:', error)
    throw new Error(error.response?.data?.message || '导出失败，请重试')
  }
}

// 生成工艺流程编码
export const generateProcessFlowCode = async (): Promise<ApiResult<string>> => {
  try {
    const response = await processApi.get('/ProcessFlow/generate-code')
    return response.data
  } catch (error) {
    console.error('生成工艺流程编码失败:', error)
    // 如果后端不可用，使用本地编号生成逻辑
    console.log('后端不可用，使用本地编号生成逻辑')
    return {
      code: 200,
      msg: '使用本地编号生成',
      data: generateLocalProcessFlowCode()
    }
  }
}

// 本地编号生成逻辑
const generateLocalProcessFlowCode = (): string => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const milliseconds = String(now.getMilliseconds()).padStart(3, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  // 格式: PF-YYYYMMDD-HHMMSS-MMM-XXX
  // 添加毫秒数确保同一秒内生成的编号也是唯一的
  return `PF-${year}${month}${day}-${hours}${minutes}${seconds}-${milliseconds}-${random}`
}

export default processApi 